package com.sticktogether.server;

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.widget.Toast;

import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.sticktogether.LogoutActivity;
import com.sticktogether.MapViewActivity;
import com.sticktogether.R;
import com.sticktogether.SigninActivity;
import com.sticktogether.multiphotoselect.MultiPhotoSelectActivity;
import com.sticktogether.multiphotoselect.ShowAlbumsActivity;
import com.sticktogether.navigation.Navigation;
import com.sticktogether.photoreceiver.PhotoDatabase;
import com.sticktogether.pushnotifications.ConnectionDetector;
import com.sticktogether.pushnotifications.Register;
import com.sticktogether.services.GpsService;
import com.sticktogether.services.UploadService;
import com.sticktogether.usermanagement.Member;

import static com.sticktogether.pushnotifications.GCMIntentService.generateNotification;


public class ServerCommunication extends AsyncTask<String, Integer, String> {
	
	// This activity is opened after a login was successful
	private static final Class<LogoutActivity> screenAfterLogin = LogoutActivity.class;
	// The path to our server backend
	private static final String domain = "http://www.wirhassenalledenjul.de/android/communicate.php";
	// A list with all members to display on the map
	@SuppressLint("UseSparseArrays")
	public static Map<Integer, Member> members = new HashMap<Integer, Member>();
	public static Map<String, Integer> usernameToUserid = new HashMap<String, Integer>();
	// A list with all pins displayed on the map
	public static Map<String, Marker> pins = new HashMap<String, Marker>();
	// A list of the titles and ids of all albums
	public static LinkedList<String> albumnames = new LinkedList<String>();
	public static ArrayList<Integer> albumids = new ArrayList<Integer>();
	public static int albumid = 0;
	public static int topicid = 0;
	public static String albumname;
	// The activity that has called us
	public static Context context;
	// The service that has called us
	public static GpsService currentService;
	//The "logging in" dialog
	private static ProgressDialog dialog;
	public static MapViewActivity map;
	// this variable is used if we have selected a member or marker in the memberlist
	// We zoom to the member or marker after we have created it (in the mapviewactivity)
	// We set this variable to 1 if we have selected a member and we set it to 2 if we have selected a marker
	public static int showInfoWindow = 0;
	private static PhotoDatabase photos;
	
	
	/**
	 * This method is called after a login was successful
	 * It is called in both cases:
	 * - There was a user_id and password stored on the device and they are (still) correct.
	 * - A username and password have been entered and they are correct.
	 */
	private static void loginSuccessful() {
    	// Start the GPS service if tracking is enabled
    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
    	if(sharedPref.getBoolean("tracking_enable", true)) {
			Intent Serviceintent = new Intent(context, GpsService.class);
	    	context.startService(Serviceintent);
    	}
    	
    	// register for GCM
		Register.register(context);
    	
    	// Open the new activity that is stored in the global variable screenAfterLogin
		Intent intent = new Intent(context,screenAfterLogin);
    	context.startActivity(intent);
	}
	
	/**
	 * When this method is called, the user_id and the password that are stored on the device are deleted.
	 * Afterwards a message is shown.
	 */
	public static void logout() {
		
		ConnectionDetector cd = new ConnectionDetector(context.getApplicationContext());
		// Check if Internet present
		if (!cd.isConnectingToInternet() && context != null) {
			showResult(context.getString(R.string.check_internet));
			// Internet Connection is not present
			// stop executing code by return
			return;
		}
		

		// Stop the GPS service
		Intent Serviceintent = new Intent(context, GpsService.class);
    	context.stopService(Serviceintent);
	    	

		// unregister from GCM
		Register.unregister(context);
		
		// Go to login page
		Intent intent = new Intent(context,SigninActivity.class);
		intent.putExtra("logout", true);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
	
	/**
	 * This method first checks if the given username exists
	 * If not a message is shown and the login process is canceled
	 * If the username exists it is checked if the password is correct.
	 * If not a message is shown and the login process is canceld.
	 * If the username and password are correct, the corresponding user_id and the md5 hash of the password
	 * are stored locally and then the loginSuccessful() method is called.
	 * 
	 * @param activity: The activity in which the "logging in" screen should be displayed
	 * @param username: The username to check
	 * @param password: The password to check
	 */
	public static void login(Activity activity, String username, String password) {
		context = activity;
		// Show a logging in box
		dialog = ProgressDialog.show(context, "", context.getString(R.string.loggingin), true);
		
		String url = String.format("%s?username=%s&password=%s",domain,username,password);
		
		try {
			url = URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		new ServerCommunication().execute(url); 
		
	}
	
	/**
	 * The method checks if there is a userid and a md5 password hash stored on the device.
	 * If so, it calls the loginSuccessful() method 
	 * 
	 * @param: activity The activity in which the "logging in" screen should be displayed
	 */
	public static void login(Activity activity) {
		context = activity;
		
        String userid = getUserId();
        String pw = getPassword();
        if(!(userid.equals("") && pw.equals(""))) {
        	loginSuccessful();
    		
        }
	}
	
	/**
	 * Send location to server
	 * @param latitude
	 * @param longitude
	 * @param service	Service, calling this method
	 */
	public static void updateGPS(double latitude, double longitude, GpsService service) {
		currentService = service;
		context = service.getApplicationContext();

        String userid = getUserId();
        String pw = getPassword();
        String url = String.format("%s?id=%s&sid=%s&x=%s&y=%s",domain,userid,pw,latitude,longitude);
        
		try {
			url = URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		new ServerCommunication().execute(url);
	}
	
	public static void updateGPS2(double latitude, double longitude) {
		
		
        String userid = getUserId();
        String pw = getPassword();
        String url = String.format("%s?id=%s&sid=%s&x=%s&y=%s&h=1",domain,userid,pw,latitude,longitude);
        
		try {
			url = URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		new ServerCommunication().execute(url);
	}
	
	/**
	 * Get position updates from server.
	 * 
	 * @param activity	context
	 * @param state true -> we want to get position update
	 */
	public static void ReceivePositionUpdates(Context activity, boolean state) {
		context = activity;
		
        String userid = getUserId();
        String pw = getPassword();
        
        String receive = state ? "start" : "stop";
        String url = String.format("%s?id=%s&sid=%s&receive=%s",domain,userid,pw,receive);
        
        
		try {
			url = URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		new ServerCommunication().execute(url);
	}
	
	/**
	 * Puts the marker with this name (name is used as key) and coordinates into the database on the server.
	 * 
	 * @param latitude
	 * @param longitude
	 * @param name	marker name
	 */
	public static void putMarker(double latitude, double longitude, String name) {
		
        String userid = getUserId();
        String pw = getPassword();
        
        String url = String.format("%s?id=%s&sid=%s&markerx=%s&markery=%s&markername=%s&putmarker=1",domain,userid,pw,latitude,longitude,name.replaceAll(" ", "%20"));
        
        
		try {
			url = URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		new ServerCommunication().execute(url);
	}
	
	/**
	 * Deletes the marker with this name (name is used as key) from the database on the server
	 * 
	 * @param name marker name
	 */
	public static void deleteMarker(String name) {
		
        String userid = getUserId();
        String pw = getPassword();
        
        String url = String.format("%s?id=%s&sid=%s&deletemarker=1&markername=%s",domain,userid,pw,name.replaceAll(" ", "%20"));
        
        
		try {
			url = URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		new ServerCommunication().execute(url);
	}
	
	/**
	 * Moves the marker with this name (name is used as key) to these coordinates in database on the server.
	 * 
	 * @param latitude
	 * @param longitude
	 * @param name
	 */
	public static void moveMarker(double latitude, double longitude, String name) {
		
        String userid = getUserId();
        String pw = getPassword();
        
        String url = String.format("%s?id=%s&sid=%s&markerx=%s&markery=%s&markername=%s&movemarker=1",domain,userid,pw,latitude,longitude,name.replaceAll(" ", "%20"));
        
        
		try {
			url = URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		new ServerCommunication().execute(url);
	}
	
	/**
	 * Save this id and password on the device.
	 * 
	 * @param id
	 * @param password
	 */
	private static void SaveIdAndPassword(String id, String password) {
		SharedPreferences settings = context.getSharedPreferences("Config1", 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("id", id);
		editor.putString("sid", password);
		editor.commit();
	}
	
	/**
	 * Delete the id and password that is stored on the device.
	 */
	public static void deleteStoredPassword() {
		if(context!=null) {
			SharedPreferences settings = context.getSharedPreferences("Config1", 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.remove("id");
			editor.remove("sid");
			editor.commit();
		}
	}

	
	/**
	 * Get User id
	 * 
	 * @return the userId that is saved on the device
	 */
	public static String getUserId() {
        SharedPreferences settings;
        settings = context.getSharedPreferences("Config1", 0);
        
        return settings.getString("id", "") ;
	}
	
	/**
	 * @return the password the userId that is saved on the device
	 */
	public static String getPassword() {
        SharedPreferences settings;
        settings = context.getSharedPreferences("Config1", 0);
        
        return settings.getString("sid", "") ;
	}

	
	/**
	 * This method requests a list of all users that will be displayed afterwards on the map.
	 * Therefore the method createMemberList() is called after we have got a response from our server.
	 * 
	 * @return	true:	If we have been able to update the markers on the map
	 * 			false:	If the app is not running and we can't update the map
	 */
	public static boolean getMemberListFromServer() {
		
		if(context==null) {
			// We have received a GCM message about a changed position, but the app is not running.
			// So it seems like it has been killed without being able to unregister from those calls in onPause().
			return false;
		}
		
		String url = String.format("%s?id=%s&sid=%s&getuserpositions=1",domain,getUserId(),getPassword());
		
		try {
			url = URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		new ServerCommunication().execute(url);
		
		return true;
	}
	
	
	/**
	 * This method requests a list of all pins that will be displayed afterwards on the map.
	 * Therefore the method createPinMap() is called after we have got a response from our server.
	 * 
	 * @return	true:	If we have been able to update the markers on the map
	 * 			false:	If the app is not running and we can't update the map
	 */
	public static boolean getPinListFromServer() {
		
		if(context==null) {
			// We have received a GCM message about a changed position, but the app is not running.
			// So it seems like it has been killed without being able to unregister from those calls in onPause().
			return false;
		}
		
    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
    	boolean showPins = sharedPref.getBoolean("show_pins", true);
		
		if(showPins) {
			String url = String.format("%s?id=%s&sid=%s&getpins=1",domain,getUserId(),getPassword());
			
			try {
				url = URLEncoder.encode(url, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			
			new ServerCommunication().execute(url);
		}
		else if(!pins.isEmpty()) {
			// The list of pins is not empty, so we have just changed the settings and should delete all pins from the map now!
			Iterator<Entry<String, Marker>> it = pins.entrySet().iterator();
			while (it.hasNext()) {
				it.next().getValue().remove();
			}
			pins.clear();
		}
		return true;
	}
	
	
	/**
	 * This method requests a list of all albums to which we can upload images.
	 * @param activity 
	 * 
	 * @return	true:	If we have been able to update the markers on the map
	 * 			false:	If the app is not running and we can't update the map
	 */
	public static void getAlbumListFromServer(Activity activity) {
		context = activity;
		String url = String.format("%s?id=%s&sid=%s&getalbums=1",domain,getUserId(),getPassword());
		
		try {
			url = URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		new ServerCommunication().execute(url);

	}
	
	/**
	 * This method creates a new album
	 * @param albumName
	 */
	public static void addAlbum(String albumName, Activity activity) {
		context = activity;
		String url = String.format("%s?id=%s&sid=%s&newalbum=%s",domain,getUserId(),getPassword(),albumName);
		try {
			url = URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		new ServerCommunication().execute(url);
	}
	
	public static void updateNotificationTable(String postid, String topicid, Context context2) {
		context = context2;
		String url = String.format("%s?id=%s&sid=%s&postid=%s&topicid=%s",domain,getUserId(),getPassword(),postid,topicid);
		try {
			url = URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		new ServerCommunication().execute(url);
	}
	
	/**
	 * This method creates a new album
	 * @param albumName
	 */
	public static void getAlbumId(String time, Context activity) {
		context = activity;
		String url = String.format("%s?id=%s&sid=%s&timetoalbum=%s",domain,getUserId(),getPassword(),time);
		url = url.replaceAll(" ", "%20");
		try {
			url = URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		new ServerCommunication().execute(url);
	}
	

	/**
	 * Here we communicate with the server in a background thread.
	 * 
	 * @return serverresponse Response from server 
	 */
	@Override
	protected String doInBackground(String... urls) {
		HttpEntity result = null;

		for (String url : urls) {
			try {
				// This is a try for a possible solution for OutOfMemoryError
				// compare http://stackoverflow.com/questions/5358014/android-httpclient-oom-on-4g-lte-htc-thunderbolt
				
				// Set the timeout in milliseconds until a connection is established.
				int timeoutConnection = 5000;

				// Set the default socket timeout (SO_TIMEOUT) 
				// in milliseconds which is the timeout for waiting for data.
				int timeoutSocket = 4000;

				// set timeout parameters for HttpClient 
				HttpParams httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
				HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
				HttpConnectionParams.setSocketBufferSize(httpParameters, 8192);//setting setSocketBufferSize

				DefaultHttpClient client = new DefaultHttpClient();
				client.setParams(httpParameters);
				
				HttpGet get = new HttpGet(URLDecoder.decode(url, "UTF-8"));
				HttpResponse responseGet = client.execute(get);
				result = responseGet.getEntity();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		String serverresponse = null;
		
		if(result != null) {
			//use the result message
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new InputStreamReader(result.getContent()));
			} catch (IllegalStateException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			

			try {
				if(reader != null){
					serverresponse = reader.readLine();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return serverresponse;
	}

	/**
	 * We have got an answer from the server...
	 * So let's see what it is.
	 */
	protected void onPostExecute(String serverresponse) {
		if(serverresponse != null) {
			
			String[] arr = serverresponse.split(":",2);
			if(arr != null && arr[0].equals("loginsuccessfull")){
				// Success
				if (arr.length>1) {
					//We have just logged in the first time, so we have to save id and password on the device. 
					arr = serverresponse.split("id:");
					String id = arr[1].split(",")[0];
					arr = serverresponse.split("password:");
					String password = arr[1].split(",")[0];
					SaveIdAndPassword(id, password);
				}
				loginSuccessful();
			}
			else if(arr != null && arr[0].equals("updategpssuccessfull")) {
				// GPS-data stored successfully. Nothing to do here.
			}
			else if(arr != null && arr[0].equals("insertmarkersuccessfull")) {
				// We have stored a new pin on the server, so refresh all the pins on our device to show this pin
				getPinListFromServer();
			}
			else if(arr != null && arr[0].equals("updateuserreceivesuccessfull")) {
				// state if we receive gcm for location changes changed. Nothing to do here.
			}
			else if(arr != null && arr[0].equals("savenotificationsuccessful")) {
				// The server has saved that we have displayed a notification. Nothing to do here.
			}
			else if(arr != null && arr[0].equals("getgpssuccessful")) {
				createMemberList(arr[1]);
			}
			else if(arr != null && arr[0].equals("getpinssuccessful")) {
				createPinsList(arr[1]);
			}
			else if(arr != null && arr[0].equals("albumid")) {
				updateAlbumId(arr[1]);
			}
			else if(arr != null && arr[0].equals("getalbumssuccessful")) {
				createAlbumsList(arr[1]);
			}
			else if(arr != null && arr[0].equals("createalbumssuccessful")) {
				showResult("album erstellt");
				getAlbumListFromServer((Activity)context);
			}
			else if(arr != null && arr[0].equals("error")){
				// The user has typed in an username that does not exist in the database
				if(arr[1].equals("userdoesnotexist")) showResult(context.getString(R.string.notexist_username));
				// The unsername that was entered exists, but the password is wrong, or the user is not active
				else if(arr[1].equals("passwordwrongorusernotactive")) 
					showResult(context.getString(R.string.password_wrong));
				// The password that is stored on our device is not right anymore
				else if(arr[1].equals("storedpasswordwrong")) {
					logout();
				}
				else if(arr[1].equals("markeralreadyexists")) {
					showResult(context.getString(R.string.pin_already_exists));
				}
				else showResult(context.getString(R.string.unexpected_error) + arr[1]);
			}
			else {
				// There was a completely unexpected response, most likely 404
				showResult(context.getString(R.string.server_not_available));
			}
		} else {
			SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
			if(sharedPref.getBoolean("show_server_errors", false)) {
	    		showResult(context.getString(R.string.check_internet));
	    	}
		}
		//dismiss the logging in dialog
		if (dialog!=null) dialog.dismiss();
	}
	
	/**
	 * OK we have got a String from the server that contains the list of users we want to display.
	 * So let's split the string and get the values we need.
	 * 
	 * @param serverResult: String containing server result
	 */
	private void createMemberList(String serverResult) {
		// If we already have markers on the map, delete all of them
		Iterator<Map.Entry<Integer, Member>> it = members.entrySet().iterator();
		while (it.hasNext()) {
			it.next().getValue().mMarker.remove();
		}
		
		// Delete the existing List, as we want to have a complete fresh one
		members.clear();
		usernameToUserid.clear();
		
    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
    	boolean showPictures = sharedPref.getBoolean("show_pictures", true);
		
		// Let's have a look at the server response
		String[] arr = serverResult.split(";");
		for(int i=0; i<arr.length; i++) {
			final String[] values = arr[i].split(",");
			final int userid = Integer.parseInt(values[0]);
			boolean isItMyOwnMarker = userid==Integer.parseInt(ServerCommunication.getUserId());
			
			if(!values[5].equals("nopic") && showPictures) {
				new AsyncTask<String, Integer, Bitmap>() {
					@Override
					protected Bitmap doInBackground(String... params) {
						final int scalefactor = 2;
						String url = "http://www.wirhassenalledenjul.de/images/avatars/" + values[5];
						return resizeBitmap(Navigation.getBitmapFromURL(url),scalefactor*MapViewActivity.mMarkerWidth, scalefactor*MapViewActivity.mMarkerHeight);
					}
				     protected void onPostExecute(Bitmap bitmap) {
				 		BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bitmap);
				    	Member member = new Member(userid, values[1], values[2], Float.parseFloat(values[3]), Float.parseFloat(values[4]),bitmapDescriptor);
						members.put(userid, member);
						usernameToUserid.put(member.getUsername(), userid);
						map.updateMember(member);
				     }
				}.execute("");
			}
			else {
				BitmapDescriptor bitmapDescriptor = isItMyOwnMarker ? BitmapDescriptorFactory.fromResource(R.drawable.my_marker) : BitmapDescriptorFactory.fromResource(R.drawable.marker);
				Member member = new Member(userid, values[1], values[2], Float.parseFloat(values[3]), Float.parseFloat(values[4]),bitmapDescriptor);
				members.put(userid, member);
				usernameToUserid.put(member.getUsername(), userid);
			}
		}
		map.updateMembers();
		
	}
	
	/**
	 * Method to resize a bitmap to desired width and height
	 * @param original	original bitmap
	 * @param width		desired width
	 * @param height	desired height
	 * @return			resized bitmap
	 */
	private static Bitmap resizeBitmap(Bitmap original, int width, int height){
		if(original != null){
			Bitmap newBitmap = Bitmap.createScaledBitmap(original, width, height, false);
    		return newBitmap;
		}
    	else
    		return null;
	}
	
	
	/**
	 * OK we have got a String from the server that contains the list of pins we want to display.
	 * So let's split the string and get the values we need.
	 * 
	 * @param serverResult: String containing server result
	 */
	private void createPinsList(String serverResult) {
		// If we already have pins on the map, delete all of them
		Iterator<Entry<String, Marker>> it = pins.entrySet().iterator();
		while (it.hasNext()) {
			it.next().getValue().remove();
		}

		// Delete the existing List, as we want to have a complete fresh one
		pins.clear();
		
		// Let's have a look at the server response
		String[] arr = serverResult.split(";");
		for(int i=0; i<arr.length; i++) {
			String[] values = arr[i].split(",");
			MarkerOptions mo = new MarkerOptions()
				.position(new LatLng(Double.parseDouble(values[2]), Double.parseDouble(values[3])))
				.draggable(true)
				.title(values[0])
				.snippet(context.getString(R.string.created_by) + " " + values[1]);
			pins.put(values[0], map.showPin(mo));
		}
		
	}
	
	
	/**
	 * OK we have got a String from the server that contains the list of albums.
	 * So let's split the string and get the values we need.
	 * 
	 * @param serverResult: String containing server result
	 */
	private void createAlbumsList(String serverResult) {

		// Delete the existing List, as we want to have a complete fresh one
		albumnames.clear();
		albumids.clear();
		
		albumnames.add(context.getString(R.string.image_create_album));
		
		// Let's have a look at the server response
		String[] arr = serverResult.split(";");
		for(int i=0; i<arr.length; i++) {
			String[] values = arr[i].split(",");
			albumnames.add(values[1]);
			albumids.add(Integer.parseInt(values[0]));
		}
		if(context instanceof ShowAlbumsActivity)
		((ShowAlbumsActivity) context).buildList();
	}
	
	
	public static PhotoDatabase getPhotoDb(Context activity) {
		if(photos==null){
			context = activity;
			photos = new PhotoDatabase(context);
		}
		return photos;
	}
	
	private void updateAlbumId(String serverResult) {
		
		// Let's have a look at the server response
		String[] arr = serverResult.split(",");
		int topicid = Integer.parseInt(arr[0]);
		String time = arr[1];
		
		PhotoDatabase photoDB = getPhotoDb(context);
		synchronized (photoDB) {
			SQLiteDatabase db = photoDB.getWritableDatabase();
		
			// the photo was not taken during an event
			// delete it form database
			if(topicid == -1) {
				db.delete("photos", "time = '" + time + "'", null);
			}
			// the photo was taken during an event.
			
			else {

				
				// check if auto upload is enabled
		    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
				if(sharedPref.getBoolean("auto_upload_enable", false)) {
					// Upload the picture
					
					// Save the album id for this event.
				    ContentValues values = new ContentValues();
				    values.put("album_id", topicid);
				    values.put("istopicid", 1);
				    db.update("photos", values, "time = '" + time + "'", null);
					Intent Serviceintent = new Intent(context, UploadService.class);
					
					context.startService(Serviceintent);
				}
				else {
					// Display a notification
					
					// remove the entry from the database
					db.delete("photos", "time = '" + time + "'", null);
					
					String albumtitle = arr[2];
					
					Intent resultIntent = new Intent(context,MultiPhotoSelectActivity.class);
					String title = albumtitle;
 					String text = context.getString(R.string.image_album_question);
 					String ticker = String.format(context.getString(R.string.image_album_question_ticker, albumtitle));
 					resultIntent.putExtra("topicid", topicid);
 					resultIntent.putExtra("albumtitle", albumtitle);
 					generateNotification(context, -500 - topicid, resultIntent, title, text, ticker, R.drawable.stub_image, null, false);
				}
				
				
			}
			db.close();
		}
		
	}

	/**
	 * Displays a toast message
	 * This was mainly for testing, but is still need sometimes in the app
	 * 
	 * @param message String that is shown in the Toast message
	 */
	private static void showResult(String message) {
		if(context != null)
		Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
		else if(currentService != null) 
		Toast.makeText(currentService, message, Toast.LENGTH_SHORT).show();
	}



}
